package com.emc.atmos.test;


import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;

import org.apache.log4j.Logger;

import com.emc.atmos.test.messaging.AtmosRequestMessage;
import com.emc.atmos.test.AtmosExMetaGateway;


@Path("/objects")
public class AtmosJig {
	
	private static Logger log = Logger.getLogger(AtmosJig.class);
	
	/**
	 * Here's what we get from the client
	* 1  POST /rest/objects HTTP/1.1
	* 2  accept: * / *
	3  x-emc-useracl: john=FULL_CONTROL,mary=READ
	4  date: Wed, 18 Feb 2009 16:03:52 GMT
	5  content-type: application/octet-stream
	6  x-emc-date: Wed, 18 Feb 2009 16:03:52 GMT
	7  x-emc-groupacl: other=NONE
	8  host: 168.159.116.96
	9  content-length: 211
	10 x-emc-uid: 33115732f3b7455d9d2344ddd235f4b9/user1
	11 x-emc-signature: KpT+3Ini1W+CS6YwJEAWYWvIlIs=
		NOTE: signature calculation -> signature = Base64(HMACSHA1(HashString))
	*/
	
	/**
	 * 
	 * @param headers
	 * @param message
	 * @return: response message for createObject
	 */
	@POST
	public Response createObject(@Context HttpHeaders headers,
								@Context UriInfo uriInfo,
								byte [] message) {
		
		//stop logging the payload
		//log.info("received message: " + message);
		
		Response response = null;
		
		// parse out this request so we can work with it
		AtmosRequestMessage atmosRequestMsg = 
				new AtmosRequestMessage(headers, uriInfo, "POST");
				//new AtmosRequestMessage(headers, uriInfo, message, "POST");

		// now authenticate the request
		AtmosAuth atmosAuth = new AtmosAuth();
		Boolean authenticated = atmosAuth.authenticateRequest(atmosRequestMsg);
		
		int status = 1;
		
		if (authenticated) {
			
			//load the props for the extended database connection attributes
			Properties props = new Properties();
			try{
				//FileInputStream propfile = new FileInputStream("atmosjig.properties");
				InputStream propfile = this.getClass().getClassLoader().getResourceAsStream("atmosjig.properties");
				//FileInputStream propfile = new FileInputStream(this.getClass().getClassLoader().getResourceAsStream("atmosjig.properties"));
				
				try{
					props.load(propfile);
				} catch (Exception e){
					props.load(propfile);
				}
				propfile.close();
			} catch (Exception e){
				log.error("error loading properties for worker.");
				log.error(e.getMessage());
			}
		
		
			//init the uploader and such...
			//AtmosUploader myUploader = new AtmosUploader("localhost",80,"tset","setset");
			AtmosUploader myUploader = new AtmosUploader("10.67.163.187",80,atmosRequestMsg.getHdrEMCUid(),atmosAuth.getSharedSecret(atmosRequestMsg.getHdrEMCUid()));
			String oid = null;
			
			//get the message into a inputstream
			//InputStream tempis = new ByteArrayInputStream(message.getBytes());
			//?InputStream tempis = new ByteArrayInputStream(message);

			//upload the object
			//try {
				//oid = myUploader.UploadObjectRetOID(tempis,tempis.available());
				oid = myUploader.UploadObjectRetOID(message,1);

			//} catch (IOException e) {
			//	// TODO Auto-generated catch block
			//	e.printStackTrace();
			//}
			
			if (!oid.isEmpty())
			{
				/*
				String tempMetaString = atmosRequestMsg.getHdrEMCListableMeta();
				tempMetaString.replaceAll("\\W", "");
				String [] tempar = tempMetaString.split(",");
				String [] metaNameValueAr = new String[tempar.length * 2];
				int count=0;
				for (String tempstr : tempar)
				{
					metaNameValueAr[count] = tempstr.split("=")[0];
					count++;
					metaNameValueAr[count] = tempstr.split("=")[1];
					count++;
				}
				
				AtmosExMeta myExMeta = new AtmosExMeta(oid,props.getProperty("atmosjigUrl"),props.getProperty("atmosjigUsername"),
										props.getProperty("atmosjigPassword"),metaNameValueAr);
				status = myExMeta.UploadExMeta();
				*/
				
				String tempMetaString = atmosRequestMsg.getHdrEMCListableMeta();
				tempMetaString = tempMetaString.replaceAll("\\s+", "");
				AtmosExMetaGateway myExMetaGW = new AtmosExMetaGateway(oid,tempMetaString.getBytes());
				status = myExMetaGW.AtmosExMetaGatewayPut();
				
			} else {
				//failed objectIDUpload
			}
			
			
				// We didn't do anything, ... well now we did hopefully
				// but we are going to tell the client that we did.
				if (status == 0)
				{
					AtmosResponseGenerator rg = new AtmosResponseGenerator();
					response = rg.genCreateObjectResponse(oid);
					
					log.info("atmosJig - response headers - " + response.getStatus() + " - " + response.getMetadata());
				} else {
					
					// for now respond anyways
					AtmosResponseGenerator rg = new AtmosResponseGenerator();
					response = rg.genCreateObjectResponse("BADBADBAD");
					
					log.info("atmosJig - response headers - " + response.getStatus() + " - " + response.getMetadata());
				}
		} else {
			// generate a response message stating we failed authentication
			// i'm not sure what this one looks like.  We need to run a sample through
			// atmos and see.
		}
		
		return response;
	}
	

	/**
	 * 
	 * @param headers
	 * @param message
	 * @return: a list of objects - build list with jdom
	 */
	@GET
	public Response listObject(@Context HttpHeaders headers,
									UriInfo uriInfo,
									String message) {
		Response response = null;
		
		
		// parse the message
		AtmosRequestMessage atmosRequestMsg = 
					new AtmosRequestMessage(headers, uriInfo, "GET");
					//new AtmosRequestMessage(headers, uriInfo, message, "GET");

		// now authenticate the request
		AtmosAuth atmosAuth = new AtmosAuth();
		Boolean authenticated = atmosAuth.authenticateRequest(atmosRequestMsg);
		
		if (authenticated) {
			// get me a list of object ids that match the search criteria.
			
			if (atmosRequestMsg.getHdrEMCIncludeMeta().equals("1") || atmosRequestMsg.getHdrEMCIncludeMeta().equals("true")) {
				// they want metadata in the response
				
			} else {
				// they don't want metadata in the response, just oids
				
			}
			
		} else {
			// generate a "failed authentication message"
			// i'm not sure what these look like out of atmos
		}
		
		return response;
	}
	
}
